package cli;

import cli.command.*;
import cli.state.*;
import cli.view.TextEffects;

import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class CommandLineInterface {
    private CurrentPath currentPath = new CurrentPath();
    private AtomicBoolean exitFlag = new AtomicBoolean(false);
    private Scanner in = new Scanner(System.in);
    private PrintWriter out = new PrintWriter(System.out, true);

    public Command dispatch(String command) {
        switch (command) {
            case "cat":
                return new Concatenate(out, in, currentPath.get());
            case "cd":
                return new ChangeDirectory(out, currentPath);
            case "cp":
                return new Copy(in, out, currentPath.get());
            case "exit":
                return new Exit(exitFlag);
            case "find":
                return new Find(out, currentPath.get());
            case "ls":
                return new ListContent(out, currentPath.get());
            case "mkdir":
                return new MakeDirectory(out, currentPath.get());
            case "mv":
                return new Move(out, currentPath.get());
            case "rm":
                return new Remove(in, out, currentPath.get());
            case "secure":
                return new Secure(in, out, currentPath.get());
            case "stat":
                return new ShowStatus(out, currentPath.get());
            case "touch":
                return new Touch(out, currentPath.get());
            case "zip":
                return new Zip(out, currentPath.get());
            default:
                return null;
        }
    }

    public void run() {
        while (!exitFlag.get()) {
            out.printf(currentPath.get()+"> ");
            String line = in.nextLine();
            String[] words = line.trim().split("\\s+");
            Command command = dispatch(words[0]);
            if (command == null) {
                out.println("命令不存在！");
            } else {
                String[] args = Arrays.copyOfRange(words, 1, words.length);
                try {
                    command.handle(args);
                } catch (Exception e) {
                    out.println("命令"+line+"执行时发生错误！");
                    e.printStackTrace();
                    continue;
                }
            }
        }
        out.println("退出成功。");
    }

    public static void main(String[] args) {
        CommandLineInterface cli = new CommandLineInterface();
        cli.run();
    }
}
